package com.guc.web;

import com.guc.dao.Dao;
import com.guc.pojo.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/u")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //保存数据到servletcontext中，全局
        ServletContext sc = getServletContext();
        //保存数据
        sc.setAttribute("msg","全局变量");
        //获取用户的登录信息、注册  opr
        String opr = req.getParameter("opr");
        if(opr!=null&opr.equals("login")){
            //获取用户的用户名密码
            String name = req.getParameter("name");
            String pwd = req.getParameter("pwd");
            //登录  对比用户名，密码  与数据对比  jdbc
            if(name!=null&&pwd!=null&&name.equals(Dao.user.getName())&&pwd.equals(Dao.user.getPwd())){
                //用户名，密码一致   登录成功
                //把用户保存到session
                HttpSession session = req.getSession();
                User u = new User(name,pwd);
                session.setAttribute("loginuser",u);
                //重定向
                resp.sendRedirect("info.jsp");
            }else{
                //把登录失败的信息转发到页面
                req.setAttribute("msg","你用户名密码错误，登录失败");
                req.getRequestDispatcher("info.jsp").forward(req,resp);
            }

        }else if(opr!=null&opr.equals("adduser")){
            //获取用户的用户名密码
            String name = req.getParameter("name");
            String pwd = req.getParameter("pwd");
            //判断用户名密码是否符合格式  ！=null
            if(name!=null&&pwd!=null){
                //注册用户
                User user= new User(name,pwd);
                //保存
                Dao.user = user;
                req.setAttribute("msg","注册成功，请登录");
                req.getRequestDispatcher("info.jsp").forward(req,resp);
            }else{
                //把登录失败的信息转发到页面
                req.setAttribute("msg","你输入的用户名密码为空，不能注册，请重新输入。");
                req.getRequestDispatcher("info.jsp").forward(req,resp);
            }
        }else{
            //把登录失败的信息转发到页面
            req.setAttribute("msg","用户注册成功，请加入登录页面，进行登录操作");
            req.getRequestDispatcher("info.jsp").forward(req,resp);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
